<template>
  <div>
    <template v-if="type === 'imglist'">
      <el-upload v-model:file-list="fileList" list-type="picture-card" :limit="1" :auto-upload="false" disabled>
        <div class="masker" @click="openSelectBox">
          <el-icon size="28" color="#b5b6b9">
            <Plus />
          </el-icon>
        </div>
        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon><zoom-in /></el-icon>
              </span>
              <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
    </template>
    <template v-else>
      <el-upload v-model:file-list="fileList" type="picture" :show-file-list="false" :auto-upload="false" disabled>
        <div class="select_box" :style="comStyle">
          <!-- v-if="realImgUrl" -->
          <div class="img_wrap" v-if="realImgUrl">
            <div class="cover">
              <span class="preview" @click="handlePreviewSingle">
                <el-icon color="white" size="20px">
                  <zoom-in />
                </el-icon>
              </span>
              <span class="remove" @click="handleRemoveSingle">
                <el-icon color="white" size="20px">
                  <Delete />
                </el-icon>
              </span>
            </div>
            <img :src="realImgUrl" class="avatar" />
          </div>
          <div class="masker" @click="openSelectBox" v-else>
            <el-icon size="28" color="#b5b6b9">
              <Plus />
            </el-icon>
          </div>
        </div>
      </el-upload>
    </template>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <Dialog ref="ImgSelectorDialogRef" title="图片库" width="70%" @confirm="handleDiaConfirm">
      <template v-slot:content>
        <ImageLib :openInDialog="true" @onChange="handleChange"></ImageLib>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
/** imports */
// @ts-ignore
import Dialog from '@/components/Dialog/index.vue'
import { ref, reactive, computed, watch } from 'vue'
// @ts-ignore
import ImageLib from '@/views/UsualManage/UploadImage/index.vue'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps, UploadUserFile, UploadFile } from 'element-plus'

interface IProps {
  width?: string | number,
  height?: string | number,
  imgUrl?: string,
  imgList?: string[], // imgList 必须要是url组成的字符串数组['www.baidu.com']这种
  type: 'img' | 'imglist',
  limit?: number // 允许上传的最大文件数量,默认一张
}

const props = withDefaults(defineProps<IProps>(), {
  width: '148px',
  height: '148px',
  type: 'img',
  limit: 1
})

/** 变量 */
const ImgSelectorDialogRef = ref(null)
const isFirst = ref(true) // 是否为第一次，为了控制watch与图片上传产生的逻辑冲突
const comStyle = computed(() => {
  return `width:${props.width};height:${props.height};`
})
const emit = defineEmits(['update:imgUrl', 'update:imgList'])

const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const tempImgUrl = ref('')
const realImgUrl = ref('')

/**
 * @breif: 初始化页面(主要是初始化图片列表)
 * @return {*}
 */
const initPage = () => {
  if (props.type === 'img') {
    if (props.imgUrl) {
      realImgUrl.value = props.imgUrl
    }
  } else {
    if (props.imgList?.length) {
      props.imgList.forEach(item => {
        fileList.value.push({ name: '', url: item })
      })
    }
  }
}
initPage()

watch(() => props.imgUrl, (newVal, oldVal) => {
  realImgUrl.value = props.imgUrl
})

// 监听多张图片，并初始化显示
watch(() => props.imgList, (newVal, oldVal) => {
  if (isFirst.value) {
    props.imgList?.forEach(item => {
      if (typeof item === 'string') {
        fileList.value.push({ name: '', url: item })
      } else {
        fileList.value.push(item)
      }
    })
  }
})

/** 多张图片的删除 */
const handleRemove = (file: UploadFile) => {
  const itemIndex = fileList.value.findIndex(item => item.url === file.url)
  fileList.value.splice(itemIndex, 1)
  emit('update:imgList', fileList.value)
}

/** 多张图片的预览 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const openSelectBox = () => {
  // @ts-ignore
  ImgSelectorDialogRef.value.visiableDialog()
}

const handleChange = (imgUrl) => {
  tempImgUrl.value = imgUrl
}

/**
 * @breif: 确认选择图片
 * @return {*}
 */
const handleDiaConfirm = () => {
  realImgUrl.value = tempImgUrl.value
  if (props.type === 'img') {
    emit('update:imgUrl', realImgUrl.value)
  } else {
    fileList.value.push({ name: '', url: realImgUrl.value })
    isFirst.value = false
    emit('update:imgList', fileList.value)
  }

  // @ts-ignore
  ImgSelectorDialogRef.value.invisiableDialog()
}

// 单张的删除
const handleRemoveSingle = () => {
  realImgUrl.value = ''
  emit('update:imgUrl', '')
}

// 单张的预览
const handlePreviewSingle = () => {
  dialogImageUrl.value = realImgUrl.value!
  dialogVisible.value = true
}
/** 函数 */
</script>

<style lang="less" scoped>
.select_box {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #b5b6b9;
  background-color: #fafafa;
  border-radius: 4px;
  overflow: hidden;

  :deep(.el-image) {
    width: 100%;
  }

  &:hover {
    cursor: pointer;
    border: 1px dashed #7ea4f0;
  }

  .img_wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    position: relative;
  }

  .cover {
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    left: 0;
    top: 0;
    background-color: #000000;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: all .3s ease-in-out;

    .remove {
      margin-left: 16px;
    }
  }

  .img_wrap:hover>.cover {
    opacity: .4;
  }
}

.masker {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
</style>

<!--
  props 参数
  width?: string | number, // 宽度 默认 148px
  height?: string | number, // 高度 默认 148px
  imgUrl?: string, // 如果type=== img 则必传
  imgList?: string[],// 如果 type === imglist 则必传 imgList 必须要是url组成的字符串数组['www.baidu.com']这种
  type: 'img' | 'imglist', 单张图片上传 选择 img 多张选择 imgList
  limit?: number // 允许上传的最大文件数量,默认一张(ps 没有作用)
  example:
  <ImageSelector type="imglist" v-model:imgList="fileList"></ImageSelector>
  <ImageSelector type="img" v-model:imgUrl="url"></ImageSelector>
  // 有默认值的情况下，会回显图片
  const url = ref('http://localhost:3000/public/1697543059664.jpg')
  const fileList = ref(['http://localhost:3000/public/1697543059664.jpg','http://localhost:3000/public/1697543289898.png'])
  // 说明：imgList和imgUrl都是响应式的数据，因此不需要额外的函数去处理该值，直接取值即可
  如果传的是imglist类型，那么可按照下面两种方式：['www','www'], [{name:'', url:''}]
 -->
